import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../connectivity/connectivity_service.dart';
import '../sync/data_sync_service.dart';
import '../../data/database/app_database.dart';

/// 离线模式状态枚举
enum OfflineModeStatus {
  online, // 在线模式
  offline, // 离线模式
  syncing // 同步中
}

/// 离线模式管理器
class OfflineModeManager {
  static final OfflineModeManager _instance = OfflineModeManager._internal();
  factory OfflineModeManager() => _instance;
  OfflineModeManager._internal();

  // 依赖的服务
  late ConnectivityService _connectivityService;
  late DataSyncService _dataSyncService;

  // 状态控制器
  final StreamController<OfflineModeStatus> _statusController =
      StreamController<OfflineModeStatus>.broadcast();
  Stream<OfflineModeStatus> get status => _statusController.stream;
  OfflineModeStatus _currentStatus = OfflineModeStatus.online;
  OfflineModeStatus get currentStatus => _currentStatus;

  bool _isInitialized = false;
  bool _forceOfflineMode = false;

  /// 初始化管理器
  Future<void> initialize({
    required AppDatabase database,
    required ConnectivityService connectivityService,
    required DataSyncService dataSyncService,
  }) async {
    if (_isInitialized) return;

    _connectivityService = connectivityService;
    _dataSyncService = dataSyncService;

    // 监听网络状态变化
    _connectivityService.connectionStatus.listen(_onConnectivityChanged);

    // 监听数据同步状态变化
    _dataSyncService.syncStatus.listen(_onSyncStatusChanged);

    // 初始化状态
    _updateStatus(_connectivityService.isOnline
        ? OfflineModeStatus.online
        : OfflineModeStatus.offline);

    _isInitialized = true;
  }

  /// 网络连接状态变化回调
  void _onConnectivityChanged(ConnectivityResult result) {
    if (_forceOfflineMode) return;

    if (result == ConnectivityResult.none) {
      // 网络断开，切换到离线模式
      _updateStatus(OfflineModeStatus.offline);
    } else {
      // 网络连接，切换到在线模式并尝试同步数据
      _updateStatus(OfflineModeStatus.syncing);
      _dataSyncService.syncAllData();
    }
  }

  /// 数据同步状态变化回调
  void _onSyncStatusChanged(SyncStatus syncStatus) {
    if (_forceOfflineMode) return;

    switch (syncStatus) {
      case SyncStatus.completed:
        _updateStatus(OfflineModeStatus.online);
        break;
      case SyncStatus.failed:
        _updateStatus(OfflineModeStatus.offline);
        break;
      case SyncStatus.syncing:
        _updateStatus(OfflineModeStatus.syncing);
        break;
      default:
        // 保持当前状态
        break;
    }
  }

  /// 强制切换到离线模式
  void forceOfflineMode() {
    _forceOfflineMode = true;
    _updateStatus(OfflineModeStatus.offline);
  }

  /// 强制切换到在线模式
  void forceOnlineMode() {
    _forceOfflineMode = false;
    if (_connectivityService.isOnline) {
      _updateStatus(OfflineModeStatus.syncing);
      _dataSyncService.syncAllData();
    } else {
      _updateStatus(OfflineModeStatus.offline);
    }
  }

  /// 手动触发数据同步
  Future<void> manualSync() async {
    if (_currentStatus != OfflineModeStatus.offline) {
      _updateStatus(OfflineModeStatus.syncing);
      await _dataSyncService.syncAllData();
    }
  }

  /// 检查是否可以执行离线操作
  bool canPerformOfflineOperation() {
    return _currentStatus == OfflineModeStatus.offline || 
           _currentStatus == OfflineModeStatus.syncing ||
           _forceOfflineMode;
  }

  /// 获取离线数据状态信息
  Future<Map<String, int>> getOfflineDataStats() async {
    // 这里可以实现获取各种数据表的记录数
    // 暂时返回模拟数据
    return {
      'users': 10,
      'projects': 5,
      'todos': 50,
      'notes': 20,
    };
  }

  /// 更新状态
  void _updateStatus(OfflineModeStatus status) {
    _currentStatus = status;
    _statusController.add(status);
  }

  /// 释放资源
  void dispose() {
    _statusController.close();
  }
}

/// Riverpod Provider for OfflineModeManager
final offlineModeManagerProvider = Provider<OfflineModeManager>((ref) {
  final manager = OfflineModeManager();
  ref.onDispose(() {
    manager.dispose();
  });
  return manager;
});